<template>
    <div class="linkc-mall-setting-box">
        <div class="linkc-mall-setting">
            <div class="box-title">
                <h4>{{ $t('order.setting.mail') }}</h4>
            </div>
            <!-- 支付设置 -->
            <div class="card_view">
                <div class="card_setting">
                    <h4>{{ $t('order.setting.pay') }}</h4>
                     <el-checkbox-group v-model="payCheck" @change="changePayType">
                        <el-checkbox :label="1" style="width: 120px">{{ $t('order.setting.online') }}</el-checkbox>
                        <p><i18n path="order.setting.t8"><el-button place="data1" type="text" @click="handleOpenPayMenuTab" class="link">{{ $t('order.setting.onlineSetting') }}</el-button></i18n></p>
                        <el-checkbox :label="2" style="width: 120px">{{ $t('order.setting.quotaSettle') }}</el-checkbox>
                        <p>{{ $t('order.setting.t1') }}</p>
                        <!-- <el-checkbox v-if="isMemberAuth" :label="4" style="width: 120px">{{ $t('order.setting.quotaSettle') }}</el-checkbox>
                        <p v-if="isMemberAuth">开启会员管理后，消费者可以使用额度进行支付，每月管理员进行财务结算</p> -->
                    </el-checkbox-group>
                </div>
            </div>
            <!-- 退款审批设置 -->
            <div class="card_view">
                <div class="card_setting">
                    <h4>{{$t('order.setting.title10')}}</h4>
                    <div class="user-tag" @click="chooseArea">
                        <template v-if="users.length">
                            <el-tag
                                v-for="item in users"
                                :key="item.userId"
                                type="info">
                                <img :src="item.logo || item.head || defaultAvatar">
                                <template v-if="isOpenData && item.staffId">
                                <open-data :openid="item.staffId"></open-data>
                                </template>
                                <template v-else>{{item.name || item.displayName}}</template>
                            </el-tag>
                        </template>
                        <template v-else>
                            <span class="placeholder">{{$t('common.base.pleaseSelect')}}</span>
                        </template>
                        <i class="iconfont icon-down"></i>
                    </div>
                </div>
            </div>
            <!-- 出库设置 -->
            <div class="card_view" style="border: none;">
                <div class="card_setting">
                    <h4>{{ $t('order.setting.qutbound') }}</h4>
                    <p>{{ $t('order.setting.t2') }}</p>
                </div>
                <div class="search_view" style="display: flex; justify-content: space-between;">
                    <el-button type="primary" icon="el-icon-plus" @click="openStoreHouse">{{ $t('common.base.add2')}}</el-button>
                </div>
                <el-table header-row-class-name="common-list-table-header__v2 table-header" :data="myWareHouseList" border :height="tableContainerHeight">
                    <el-table-column type="index" width="100" align="center" :label="$t('common.base.order')"></el-table-column>
                    <el-table-column
                        :label="$t('order.setting.warName')"
                        show-overflow-tooltip
                    >
                        <template slot-scope="{row}">
                        {{ row.warehouseName }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        :label="$t('common.base.operation')"
                        fixed="right"
                        width="200"
                    >
                        <template slot-scope="scope">
                            <div class="operation">
                                <i
                                    class="iconfont icon-long-arrow-up"
                                    @click="moveWarehouse(scope.$index, 'top', myWareHouseList)"
                                ></i>
                                <i
                                    class="iconfont icon-long-arrow-down"
                                    @click="moveWarehouse(scope.$index, 'down', myWareHouseList)"
                                ></i>
                                <el-button type="text" v-if="scope.$index !== 0" @click="istopWarehouse(scope.$index, scope.row.id, myWareHouseList)">{{$t('common.base.topping')}}</el-button>
                                <el-button type="text" @click="removeWarehouse(scope.row.id)">{{ $t('common.base.delete')}}</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 收货后自动完成订单 -->
            <div class="card_view">
                <div class="card_setting">
                    <h4>{{ $t('order.setting.t7')}}</h4>
                    <div class="input_setting">
                      <i18n path="order.setting.t9">
                        <el-input
                          place="data1"
                          class="num_input"
                          v-model="settingInfo.orderCompleteDays"
                          @focus="getOriginal(settingInfo.orderCompleteDays)"
                          @input="settingInfo.orderCompleteDays=settingInfo.orderCompleteDays.replace(/[^\d.]/g,'')"
                          @blur="updateOrderCompleteDays($event)"
                        >
                        </el-input>
                      </i18n>
                    </div>
                    <p>{{ $t('order.setting.t3')}}</p>
                </div>
            </div>
            <!-- 商品详情页销量 -->
            <div class="card_view">
                <div class="card_setting">
                    <h4>{{ $t('order.setting.t5')}}</h4>
                    <el-radio-group v-model="settingInfo.showSales" @change="updateShowSales">
                        <el-radio :label="1" style="width: 100px">{{ $t('common.base.show') }}</el-radio>
                        <el-radio :label="0" style="width: 100px">{{ $t('common.base.showNo') }}</el-radio>
                    </el-radio-group>
                    <p>{{ $t('order.setting.t6')}}</p>
                    <div class="input_setting" v-if="settingInfo.showSales == 1">
                        <el-checkbox v-model="settingInfo.showSalesNumberState" :checked="settingInfo.showSalesNumberState === 1" @change="updateShowSalesNumberState">
                          <i18n path="order.setting.t10">
                            <el-input
                                place="data1"
                                :disabled="!settingInfo.showSalesNumberState"
                                class="num_input"
                                v-model="settingInfo.showSalesNumber"
                                @focus="getOriginal(settingInfo.showSalesNumber)"
                                @blur="updateShowSalesNumber($event)"
                            ></el-input>
                          </i18n>
                        </el-checkbox>
                    </div>
                    <p v-if="settingInfo.showSales == 1">{{ $t('order.setting.t4')}}</p>
                </div>
            </div>
            <!-- 物流设置 -->
            <div class="card_view">
                <div class="card_setting">
                    <h4>{{ $t('order.setting.logCom') }}</h4>
                    <div class="search_view">
                        <el-button type="primary" icon="el-icon-plus" @click="openLogistics">{{ $t('common.base.add2')}}</el-button>
                    </div>
                    <el-table 
                        header-row-class-name="common-list-table-header__v2" 
                        :data="myLogisticsList" 
                        border
                        class="move-table"
                    >
                        <el-table-column type="index" width="100" align="center" :label="$t('common.base.order')" />
                        <el-table-column
                            :label="$t('common.base.logisticsCompany')"
                            show-overflow-tooltip
                        >
                            <template slot-scope="{row}">
                            {{ row.expressName }}
                            </template>
                        </el-table-column>
                        <el-table-column
                            :label="$t('common.base.operation')"
                            fixed="right"
                            width="200"
                        >
                            <template slot-scope="scope">
                                <div class="operation">
                                    <i
                                        class="iconfont icon-long-arrow-up"
                                        @click="moveLogistics(scope.$index, 'top', myLogisticsList)"
                                    ></i>
                                    <i
                                        class="iconfont icon-long-arrow-down"
                                        @click="moveLogistics(scope.$index, 'down', myLogisticsList)"
                                    ></i>
                                    <el-button type="text" v-if="scope.$index !== 0" @click="istopLogistics(scope.$index, scope.row.id, myLogisticsList)">{{ $t('common.base.topping') }}</el-button>
                                    <el-button type="text" @click="removeLogistics(scope.row.id)">{{ $t('common.base.delete') }}</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>

            <!-- 商品规格-->
            <div class="card_view">
                <div class="card_setting">
                    <h4>{{$t('goods.component.productSpecifications')}}</h4>
                    <div class="add-btn">
                        <el-button type="primary" @click="addSpecs" icon="el-icon-plus">{{ $t('common.base.create')}}</el-button>
                    </div>
                    <el-table 
                        header-row-class-name="common-list-table-header__v2" 
                        :data="specsList" 
                        border
                        class="move-table"
                    >
                        <el-table-column :label="$t('order.setting.title15')" show-overflow-tooltip>
                            <template slot-scope="{row}">
                            {{ row.specsName }}
                            </template>
                        </el-table-column>
                        <el-table-column :label="$t('order.setting.title3')" :show-overflow-tooltip="true">
                            <template slot-scope="{row}">
                                <div>
                                    <span v-for="(v, index) in row.specsValue" :key="index">
                                        {{ v }}<span v-if="index< row.specsValue.length-1">、</span>
                                    </span>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            :label="$t('common.base.operation')"
                            fixed="right"
                            width="200"
                        >
                            <template slot-scope="scope">
                                <div class="operation">
                                    <el-button type="text" @click="editSpecs(scope.row)">{{ $t('common.base.edit')}}</el-button>
                                    <el-button type="text" @click="delSpecs(scope.row)">{{ $t('common.base.delete')}}</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>

            <!-- 消息提醒设置 -->
            <div class="card_view">
                <div class="card_setting">
                    <h4>{{$t('order.setting.title11') }}</h4>
                    <p>{{$t('order.setting.title12') }}</p>
                    <div class="search_view">
                        <el-button type="primary" @click="toMessageSetting()">{{ $t('common.base.toSet')}}</el-button>
                    </div>
                </div>
            </div>
        </div>
        <!-- 选择仓库弹框 -->
        <StoreHouseDialog 
            ref="storeHouseDialogRef"
            :value="myWareHouseLists"
            @change="submitWareHouse($event)"
         />
        <!-- 选择物流弹框 -->
        <LogisticsDialog
            ref="logisticsDialogRef"
            :value="myLogisticsLists"
            @change="submitLogistics($event)"
        />
        <SpecsDialog 
            ref="specsDialog"
            @confirmSpecs="getSpecsList"
        />
        
    </div>
</template>
<script>
/* components */
import StoreHouseDialog from './components/storeHouseDialog.vue';
import LogisticsDialog from './components/changeLogisticsDialog.vue';
import SpecsDialog from './components/specsDialog.vue';
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { BaseSelectUserModeEnum } from '@src/component/common/BaseSelectUser/model/enum'
import { getOssUrl } from '@src/util/assets'
/* API */
import { getOrderConfig, updateOrderConfig, getExpressConfig, updateExpressConfig, deleteExpressConfig, saveExpressConfig, saveWareHouse, queryWarehouseList, deleteWareHouse, updateSortWareHouse, updatePaymentConfig,
    querySpecsList, deleteSpecs, checkEdit
} from '@src/api/LinkcApi';
import { t } from '@src/locales'
const defaultAvatar = getOssUrl('/avatar.png');
import { getRootWindow } from '@src/util/dom'
export default {
    name: 'linkc-mall-setting',
    components: { LogisticsDialog, StoreHouseDialog, SpecsDialog, BaseSelectUserModeEnum },
    data() {
        return {
            payCheck: [],
            myWareHouseList: [],
            myWareHouseLists: [],
            keywords: '',
            settingInfo: {},
            checked: true,
            myLogisticsList: [],
            myLogisticsLists: [],
            originalData: null,
            specsList: [],
            users: [],
            defaultAvatar,
        }
    },
    computed: {
        tableContainerHeight() {
            return this.myWareHouseList?.length > 10 ? '451px' : `${(this.myWareHouseList?.length + 1) * 41}px`;
        },
        isMemberAuth() {
            return false
            // const RootWindow = getRootWindow(window)
            // console.log(RootWindow.grayAuth)
            // return RootWindow.grayAuth?.MEMBER_MANAGE || false
        },
    },
    mounted() {
        this.getSettingInfo()
        this.getLogistics()
        this.getWarehouseList()
        this.getSpecsList()
    },
    methods: {
        // 弹框人员选择组件去选择部门和人员
        chooseArea() {
            this.$fast.select.multi.departmentAndUser({
                showServiceProvider: false,
                isCanChooseDepartment: false,
                isShowSearchServiceProviderUsers: false,
                mode: BaseSelectUserModeEnum.Filter,
                selectedAll: this.users,
                min: -1,
                isTag: true,
            }).then(result => {
                if(result.status === 0) {
                    if (result?.data?.all.length) {
                        this.users = result?.data?.all || []
                        this.changePayType(this.payCheck)
                    } else {
                        this.$message.error(this.$t('order.setting.title13'));
                    }
                }
            }).catch(err => {
                console.error(err)
            })
        },
        // 前往消息提醒
        toMessageSetting() {
            openAccurateTab({
                type: PageRoutesTypeEnum.PageSettingMessage
            })
        },
        getSpecsList() {
            querySpecsList().then(res => {
                if(res.code != 200) return this.$message.error(res.msg);
                this.specsList = res.data
            }).catch(err => {
                this.$message.error(res.msg);
            })
        },
        delSpecs(item) {
            let params = {id: item.id}
            checkEdit(params).then(res => {
                if(res.code != 200) return this.$message.error(res.msg);
                if(res.data) {
                    deleteSpecs({ id: item.id }).then(res => {
                        if(res.code != 200) return this.$message.error(res.msg);
                        this.getSpecsList()
                    }).catch(err => {
                        this.$message.error(res.msg);
                    })
                }else {
                    this.$platform.alert(this.$t('order.setting.title16'));
                }
            }).catch(err => {
                this.$message.error(res.msg);
            })
        },
        addSpecs() {
            if(this.specsList.length == 100 ) return this.$message.error(this.$t('order.setting.title14'));
            this.$refs.specsDialog.openDialog();
        },
        editSpecs(item) {
            let params = {id: item.id}
            checkEdit(params).then(res => {
                if(res.code != 200) return this.$message.error(res.msg);
                if(res.data) {
                    this.$refs.specsDialog.openDialog(item);
                }else {
                    this.$platform.alert(this.$t('order.setting.title17'));
                }
            }).catch(err => {
                this.$message.error(res.msg);
            })
            
        },
        // 获取商城设置
        getSettingInfo() {
            getOrderConfig().then(res => {
                if (res.success) {
                    this.settingInfo = res.data
                    this.settingInfo.showSalesNumberState = res.data.showSalesNumberState === 1 ? true : false
                    if (res.data.payType === 3) {
                        this.payCheck = [1,2]
                    }else if (res.data.payType === 5) {
                        this.payCheck = [1,4]
                    } else if (res.data.payType){
                        this.payCheck = [res.data.payType]
                    }
                    this.users = res.data?.refundApproveConfigVO?.approveUserConfigList || []
                } else {
                    this.$message.error(res.msg);
                }
            }).catch(err => {
                this.$message.error(res.msg);
            })
        },
        handleOpenPayMenuTab() {
            openAccurateTab({
                type:PageRoutesTypeEnum.PagePaymentSetting
            })
        },
        // 获取input元数据
        getOriginal(val) {
            this.originalData = val
        },
        // 设置支付方式
        changePayType(val) {
            let paramList = this.users.map(item => {
                return {
                    id: item.userId || item.id,
                    typeId: item?.typeId || ''
                }
            })
            if (val.length == 1) {
                this.updatePayment({payType: val[0],refundApproveConfig: {approveUserConfigList: paramList}})
            } else if (val.length == 2) {
                let payType = (val.includes(1) && val.includes(2)) ? 3 : 5
                this.updatePayment({payType: payType,refundApproveConfig: {approveUserConfigList: paramList}})
            } else {
                this.updatePayment({payType: null,refundApproveConfig: {approveUserConfigList: paramList}})
            }
        },
        updatePayment(data) {
            updatePaymentConfig(data).then(res => {
                if (res.code !== '200') {
                    console.log(res.msg)
                    this.$message.error(res.msg);
                } else {
                    this.getSettingInfo()
                }
            }).catch(err => {
                console.log(err.msg)
            })
        },
        // 更新发货后几天完成订单
        updateOrderCompleteDays(e) {
            let val = e.target.value
            if (!val) {
                val = 3
                this.settingInfo.orderCompleteDays = 3
            } else if (Math.trunc(val) <= 0 || val > 30) {
                this.$message.error(t('order.setting.m2'));
                this.settingInfo.orderCompleteDays = this.originalData
                return
            } else {
                this.settingInfo.orderCompleteDays = Math.trunc(val)
            }
            if (this.originalData !== val) {
                this.updateSetting({orderCompleteDays: Math.trunc(val)})
            }
            this.originalData = null
        },
        // 更新销量件数
        updateShowSalesNumber(e) {
            let val = e.target.value
            if (!val) {
                val = 50
                this.settingInfo.showSalesNumber = 50
            } else if (Math.trunc(val) <= 0 || val > 99999) {
                this.$message.error(t('order.setting.m1'));
                this.settingInfo.showSalesNumber = this.originalData
                return
            } else {
                this.settingInfo.showSalesNumber = Math.trunc(val)
            }
            if (this.originalData !== val) {
                this.updateSetting({showSalesNumber: Math.trunc(val)})
            }
            this.originalData = null
        },
        // 更新商城设置
        updateSetting(data) {
            updateOrderConfig(data).then(res => {
                if (res.code !== '200') {
                    console.log(res.msg)
                    this.$message.error(res.msg);
                } else {
                    this.getSettingInfo()
                }
            }).catch(err => {
                console.log(err.msg)
            })
        },
        // 更新销量设置
        updateShowSales(val) {
            this.updateSetting({showSales: val})
        },
        // 更新销量数量设置
        updateShowSalesNumberState(val) {
            this.updateSetting({showSalesNumberState: val ? 1 : 0})
        },
        clear() {
        },
        // 打开仓库弹框
        openStoreHouse() {
            this.$refs.storeHouseDialogRef.openDialog();
        },
        // 获取已保存的仓库
        getWarehouseList() {
            queryWarehouseList().then(res => {
                if (res.success && res.data) {
                    let list = JSON.parse(JSON.stringify(res.data)) || []
                    this.myWareHouseList = list || []
                    this.myWareHouseLists = res.data.length ? res.data.map(item => {
                        item.name = item.warehouseName
                        item.id = item.warehouseId
                        return item
                    }) : []
                }
            })
        },
        // 仓库排序
        async moveWarehouse(index, direction, list) {
            let lists = await this.moveTypes(index, direction, list)
            this.updateWarehouse(lists)
        },
        // 仓库置顶
        async istopWarehouse(index, id, list) {
            let lists = await this.istop(index, id, list)
            this.updateWarehouse(lists)
        },
        // 仓库排序、置顶
        async updateWarehouse(list) {
            let params = await this.sortList(list)
            updateSortWareHouse(params).then(res => {
                if (res.success) {
                    this.getWarehouseList()
                }
            })
        },
        // 删除仓库
        removeWarehouse(id) {
            deleteWareHouse({id}).then(res => {
                if (res.success) {
                    this.getWarehouseList()
                    // console.log('----', this.myWareHouseLists)
                }
            })
        },
        // 保存选择的仓库
        submitWareHouse(list) {
            saveWareHouse(list).then(res => {
                if (res.success) {
                    this.$refs.storeHouseDialogRef.closeDialog();
                    this.getWarehouseList()
                } else {
                    this.$message.error(res.msg);
                }
            }).catch(err => {
                this.$message.error(res.msg);
            })
        },
        // 打开物流弹框
        openLogistics() {
            this.$refs.logisticsDialogRef.openDialog();
        },
        // 获取已选择物流公司
        getLogistics() {
            getExpressConfig().then(res => {
                if (res.success && res.data) {
                    let list = JSON.parse(JSON.stringify(res.data)) || []
                    this.myLogisticsList = list || []
                    this.myLogisticsLists = res.data.length ? res.data.map(item => {
                        item.type = item.expressCode
                        item.name = item.expressName
                        item.id = Number(item.expressId)
                        return item
                    }) : []
                }
            })
        },
        // 物流排序
        async moveLogistics(index, direction, list) {
            let lists = await this.moveTypes(index, direction, list)
            this.updateLogistics(lists)
        },
        // 物流置顶
        async istopLogistics(index, id, list) {
            let lists = await this.istop(index, id, list)
            this.updateLogistics(lists)
        },
        // 物流排序、置顶
        async updateLogistics(list) {
            let params = await this.sortList(list)
            updateExpressConfig(params).then(res => {
                if (res.success) {
                    this.getLogistics()
                }
            })
        },
        // 删除物流
        removeLogistics(id) {
            deleteExpressConfig({id}).then(res => {
                if (res.success) {
                    this.getLogistics()
                }
            })
        },
        // 保存选择的物流
        submitLogistics(list) {
            saveExpressConfig(list).then(res => {
                if (res.success) {
                    this.$refs.logisticsDialogRef.closeDialog();
                    this.getLogistics()
                } else {
                    this.$message.error(res.msg);
                }
            }).catch(err => {
                console.error('submit logistics error', err);
            })
        },
        // 上下移动类别
        moveTypes(index, direction, list) {
            if (index === 0 && direction === "top") return;
            if (index === list.length - 1 && direction === "down") return;
            let newArr = list;
            let moveItem = newArr.splice(index, 1);
            if (direction === "top") {
                newArr.splice(index - 1, 0, moveItem[0]);
            } else {
                newArr.splice(index + 1, 0, moveItem[0]);
            }
            newArr.map((item, index) => {
                item.sortId = index + 1
            })
            return newArr
            console.log(newArr)
        },
        // 置顶
        istop(index, id, list) {
            let item = list.filter(l => { return l.id === id})
            list.splice(index, 1)
            list.unshift(item[0])
            return list
        },
        // 排序数据
        sortList(list) {
            let params = list.map((item, index) => {
                return {
                    id: item.id,
                    sortId: index + 1
                };
            });
            return params
        },
    }
}
</script>
<style lang="scss" scoped>
.linkc-mall-setting-box{
    min-width: 730px;
    padding: 20px;
    width: 100%;
    border-radius: 4px;
    .linkc-mall-setting{
        background: #ffffff;
        padding-bottom: 24px;
    }
    .box-title {
        font-weight: 600;
        font-size: 16px;
        border-bottom: 1px solid #E8E8E8;
        padding: 12px 12px 0;
        p{
            font-size: 12px;
            color: #8C8C8C;
        }
    }
    .card_view{
        margin: 0 26px;
        border-bottom: 1px dashed #E8E8E8;
        &:last-child{
            border: none
        }
        .search_view{
            margin: 0 0 12px;
            .search_input{
                width: 260px;
            }
        }
        .operation{
            .iconfont{
                color: $color-primary-light-6;
                font-size: 14px;
                margin-right: 8px;
                cursor: pointer;
            }
        }
    }
    .card_setting{
        padding: 16px 0 0;
        h4{
            position: relative;
            &::before{
                content: '';
                width: 2px;
                height: 14px;
                background: $color-primary-light-6;
                border-radius: 1px;
                position: absolute;
                top: 3px;
                left: -8px;
            }
        }
        p{
            font-size: 12px;
            color: #8C8C8C;
            margin: 8px 0 14px;
        }
        .link{
            font-size: 12px;
            padding: 0;
        }
        .input_setting{
            display: flex;
            line-height: 32px;
            margin-bottom: 10px;
            .num_input{
                width: 80px;
                margin: 0 8px;
            }
        }
        .user-tag{
            width: 488px;
            height: 32px;
            border-radius: 4px;
            display: flex;
            flex-direction: row;
            align-items: center;
            padding: 5px 12px;
            margin-bottom: 16px;
            background: #FFFFFF;
            box-sizing: border-box;
            border: 1px solid #e0e1e2;
            position: relative;
            .el-tag {
                margin: 5px 12px 5px 0
            }
            .placeholder {
                font-size: 14px;
                font-weight: 400;
                color: #BFBFBF;
                line-height: 22px;
            }
            img {
                border-radius: 50%;
                width: 24px;
                height: 24px;
                margin-right: 4px;
            }
            .iconfont{
                position: absolute;
                right: 10px;
                color: #BFBFBF;
            }
        }
        .move-table {
            margin-bottom: 14px;
        }
        .add-btn {
            margin-top: 16px;
            margin-bottom: 12px;
        }
    }
}

.linkc-mall-setting ::v-deep .el-table__header th {
    padding: 0;
    height: 40px;
}
</style>
